<?php

defined('SYSPATH') or die('Access error!');
/**
 * URL helper 类 
 */
class URL
{

    /**
     *     // 网址
     *     echo URL::base();
     *
     *     // 默认的协议
     *     echo URL::base(TRUE, TRUE);
     *
     *     //有协议的链接地址
     *     echo URL::base(TRUE, 'https');
     *
     * @param   boolean  
     * @param   mixed   
     * @return  string
     */
    public static function base($index = FALSE, $protocol = FALSE)
    {
        $base_url = Core::$base_url;

        if ($protocol === TRUE)
        {
            $protocol = Request::$protocol;
        }
        elseif ($protocol === FALSE AND $scheme = parse_url($base_url, PHP_URL_SCHEME))
        {
            $protocol = $scheme;
        }

        if ($index === TRUE AND !empty(Core::$index_file))
        {
            $base_url .= Core::$index_file . '/';
        }

        if (is_string($protocol))
        {
            if ($port = parse_url($base_url, PHP_URL_PORT))
            {
                $port = ':' . $port;
            }

            if ($domain = parse_url($base_url, PHP_URL_HOST))
            {
                $base_url = parse_url($base_url, PHP_URL_PATH);
            }
            else
            {
                $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
            }

            $base_url = $protocol . '://' . $domain . $port . $base_url;
        }

        return $base_url;
    }

    /**
     * 获取请求ip
     *
     * @return ip地址
     */
   public static function get_ip()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
        {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
        {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
        {
            $ip = getenv('REMOTE_ADDR');
        }
        elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
        {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
    }

    /**
     *  完整的链接
     *
     *     echo URL::site('foo/bar');
     *
     * @param   string  
     * @param   mixed  
     * @return  string
     * @uses    URL::base
     */
    public static function site($uri = '', $protocol = FALSE)
    {
        $path = preg_replace('~^[-a-z0-9+.]++://[^/]++/?~', '', trim($uri, '/'));

        if (!UTF8::is_ascii($path))
        {
            $path = preg_replace('~([^/]+)~e', 'rawurlencode("$1")', $path);
        }

        return URL::base(TRUE, $protocol) . $path;
    }

    /**
     *   得到一个链接参数的字符串
     *
     *     // 例如返回： "?sort=title&limit=10"
     *     $query = URL::query(array('sort' => 'title', 'limit' => 10));
     * @param   array   
     * @param   boolean 
     * @return  string
     */
    public static function query(array $params = NULL, $use_get = TRUE)
    {
        if ($use_get)
        {
            if ($params === NULL)
            {
                $params = $_GET;
            }
            else
            {
                $params = array_merge($_GET, $params);
            }
        }
        if (empty($params))
        {
            return '';
        }
        $query = http_build_query($params, '', '&');
        return ($query === '') ? '' : ('?' . $query);
    }

    /**
     * 返回一个字符串的链接组合字符串
     *
     *     echo URL::title('My Blog Post'); // "my-blog-post"
     *
     * @param   string  
     * @param   string   
     * @param   boolean  
     * @return  string
     * @uses    UTF8::transliterate_to_ascii
     */
    public static function title($title, $separator = '-', $ascii_only = FALSE)
    {
        if ($ascii_only === TRUE)
        {
            $title = UTF8::transliterate_to_ascii($title);

            $title = preg_replace('![^' . preg_quote($separator) . 'a-z0-9\s]+!', '', strtolower($title));
        }
        else
        {
            $title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', UTF8::strtolower($title));
        }

        $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);

        return trim($title, $separator);
    }
    
       /**
	 * 判断一个url是否本站的url。
	 * @param <type> $url 用于判断的url字符串
	 * @param <type> $domain 用作判断依据的主域名，如此参数未提供，则取数据库中的本站主域名。
	 */
	public static function is_our_url($url,$domain = NULL)
	{
		$url = parse_url($url);
		if(!isset($url['host']) OR preg_match('/^(([-\w\.]+)\.)?'.str_replace('.','\.',$domain).'$/', $url['host']))
		{
			return TRUE;
		}
		return FALSE;
	}

}